<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定时器练习</title>
    <script>
        window.onload = function(){
            var img = document.getElementsByTagName("img")[0];
            var start = document.getElementById("start");
            var stop = document.getElementById("stop");
            //img的src列表
            var imgArr = ["img/ex08/1.jpg","img/ex08/2.jpg","img/ex08/3.jpg","img/ex08/4.jpg","img/ex08/5.jpg","img/ex08/6.jpg"];
            //定义定时器标识
            var timer;
            //定义图片索引
            var index = 0;
            //点击开始按钮后开启定时器
            start.onclick = function(){
                //关闭上一个定时器
                //clearInterval()可传任何类型的参数
                clearInterval(timer);
                timer = setInterval(function(){
                    index++;
                    //播到最后一张返回到第一张
                    index = index % imgArr.length;
                    img.src = imgArr[index];
                },500);
            };
            //点击停止关闭定时器
            stop.onclick = function(){
                clearInterval(timer);
            };

        };
    </script>
</head>
<body>
    <img src="./img/ex08/1.jpg" >
    <br>
    <button id="start">开始</button>
    <button id="stop">停止</button>
</body>
</html>